#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :app.py
# Time  :2025/3/26 17:47
# Email :fortunatedong@163.com
# Author:by Adonli
# 初始化会话状态
import json
import os
import time
import streamlit as st
import toml
from streamlit_change_language import cst
from settings.user_role_permission import authenticate_user, get_user_permissions, load_users

cst.change(language='cn')
from config import ROOT_DIR

sidebar_logo_path = os.path.join(ROOT_DIR, 'static/logo.svg')
# web_logo_path = os.path.join(ROOT_DIR, 'static/logo.svg')
st.set_page_config(
page_title="自动化工具聚合平台",
page_icon=sidebar_logo_path,
layout="wide",
initial_sidebar_state="expanded",
menu_items={
'Get Help': 'https://www.extremelycoolapp.com/help',
'Report a bug': "https://www.extremelycoolapp.com/bug",
'About': "# This is a header. This is an *extremely* cool app!"
}
)


# 初始化会话状态
if "logged_in" not in st.session_state:
    users_role_permission = load_users()
    st.session_state.logged_in = False
    st.session_state.current_username = None
    st.session_state.current_password = None
    st.session_state.users = users_role_permission["USERS"]



def login():
    col1, col2, col3 = st.columns([1, 1, 1])
    with col2:
        st.header("登录")
        st.divider()
        username = st.text_input("用户名")
        password = st.text_input("密码", type="password")
        if st.button("Login"):
            authenticate = authenticate_user(username, password)
            if authenticate:
                st.session_state.logged_in = True
                st.session_state.current_username = username
                st.session_state.current_password = password
                st.success("登录成功!")
                time.sleep(0.5)
                st.rerun()
            else:
                st.error("用户名或密码错误")

def logout():
    if st.button("Logout"):
        st.session_state.clear()
        st.cache_data.clear()
        st.session_state.logged_in = False
        st.session_state.current_user = None
        st.session_state.current_password = None
        st.rerun()


upload_store_datas_page = st.Page("pages/upload_store_datas_page.py", title="编辑SKU—URL",)
price_warning_page = st.Page("pages/price_warning_page.py", title="价格预警",)
price_warning_setting_page = st.Page("pages/price_warning_setting_page.py", title="定时任务设置",)
jd_spider_purchase_price_page = st.Page("pages/jd_spider_purchase_price.py", title="京东采购价",)
overtime_statistics_page = st.Page("pages/overtime_statistics_page.py", title="加班统计",)
attendance_page = st.Page("pages/attendance_page.py", title="考勤统计", )
repair_bill_pdf_page = st.Page("pages/repair_bill_pdf_page.py", title="生成批量保修单",)
user_role_permission_page = st.Page("pages/user_role_permission_page.py", title="用户权限设置", )
add_month_report_table_page = st.Page("pages/add_month_report_table_page.py", title="月报总结",)
month_report_table_page = st.Page(f"pages/month_report_table_page.py", title="月报明细",)

zi_continued_provision_page = st.Page(f"pages/zi_continued_provision_page.py", title="续报备", )
zong_continued_provision_page = st.Page(f"pages/zong_continued_provision_page.py", title="续报备", )
login_page = st.Page(login, title="登录")
pg = st.navigation([login_page])
logout_page = st.Page(logout, title="退出登录")
pages = {
            "账户管理": [logout_page],
            "国铁商城比价系统": [upload_store_datas_page, price_warning_page,price_warning_setting_page],
            "京东平台工具": [jd_spider_purchase_price_page],
            "人力资源工具": [overtime_statistics_page,attendance_page,repair_bill_pdf_page],
            "子公司商务组工具":[zi_continued_provision_page],
            "总公司商务组工具":[zong_continued_provision_page],
            "工作报告": [add_month_report_table_page,month_report_table_page],
            "管理员设置": [user_role_permission_page]
        }
configs_toml = os.path.join(ROOT_DIR, 'settings/configs.toml')
PAGES_NAVIGATION_LIST = [key for key,value in pages.items()]
with open(configs_toml, "r", encoding="utf-8") as f:
    cfg = toml.load(f)
cfg['PAGES']['PAGES_NAVIGATION_LIST'] = PAGES_NAVIGATION_LIST
with open(configs_toml, 'w', encoding="utf-8") as f:
    toml.dump(cfg, f)



if st.session_state.logged_in:
    st.logo(sidebar_logo_path,size="large")
    permissions = get_user_permissions( st.session_state.current_username, st.session_state.current_password)
    navigation_init = {}
    for i in permissions["permission"]:
        page = pages[i]
        navigation_init[i] = page
    # print(navigation_init)
    pg = st.navigation(navigation_init)

pg.run()

